<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="年月" prop="plan_months">
        <el-date-picker clearable
                        v-model="queryParams.plan_months"
                        type="months"
                        value-format="yyyy-MM"
                        placeholder="选择排产月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同号" prop="contractCode">
        <el-input v-model="queryParams.contractCode" placeholder="请输入合同号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePrint">生产排产计划周打印</el-button>
      </el-form-item>
    </el-form>
<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="teamSelect"-->
<!--          @click="printPlan"-->
<!--          v-hasPermi="['factory:factorywplan:edit']"-->
<!--        >打印周计划</el-button>-->
<!--      </el-col>-->
<!--    </el-row>-->

    <el-table v-loading="loading"
              :data="teamWplanList"
              show-summary
              border style="width:100%;"
              @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="年月周" align="center" prop="monthWeek" >
        <template slot-scope="scope">
          {{scope.row.monthWeek}}
        </template>
      </el-table-column>
      <el-table-column label="排产开始日期" align="center" prop="planStartdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartdate, '{y}-{m}-{d}') }} {{scope.row.planFinishdateOfWeek}}</span>
        </template>
      </el-table-column>
      <el-table-column label="产地" align="center" prop="factoryName" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="班组名称" align="center" prop="teamName" />
      <el-table-column label="合同号" align="center" prop="contractCode" width="120" />
      <el-table-column label="订单号" align="center" prop="orderCode" />
      <el-table-column label="产品编码" align="center" prop="bomCode" />
      <el-table-column label="产品名称" align="center" prop="bomName" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="规格型号" align="center" prop="productStandard" :show-overflow-tooltip="true"/>
      <el-table-column label="下单日期" align="center" prop="orderDate" width="100"/>
      <el-table-column label="分单日期" align="center" prop="createDate" width="100"/>
      <el-table-column label="订单预计交期" align="center" prop="orderPlanFinishdate"  width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderPlanFinishdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排产完成日期" align="center" prop="planFinishdate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planFinishdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产状态" align="center" prop="workerOrderstatusDesc" />
      <el-table-column label="生产进度" align="center" prop="percentage" width="100px">
        <template slot-scope="scope">
          <el-progress :color="customColorMethod"
                       :text-inside="true"
                       :stroke-width="26"
                       :percentage="scope.row.percentage">
          </el-progress>
        </template>
      </el-table-column>
<!--      <el-table-column label="产品数量" align="center" prop="workerOrdernum"  width="80"/>-->
<!--      <el-table-column label="采样数量" align="center" prop="sampleNum" />-->
      <el-table-column label="排产数量" align="center" prop="planCapacity"  width="80px"/>
      <el-table-column label="已完工量" align="center" prop="finishedNum" width="80px"/>
      <el-table-column label="待完工量" align="center" prop="unFinishedNum" width="80px">
        <template slot-scope="scope">
          {{scope.row.planCapacity - (scope.row.finishedNum?scope.row.finishedNum:0)}}
        </template>
      </el-table-column>
      <el-table-column label="金蝶入库" align="center" prop="finishedCount" width="80px" />
      <el-table-column label="生产入库" align="center" prop="instoreNum" width="80px" />
      <el-table-column label="生产工单" align="center" prop="workerorderCode" />
<!--      <el-table-column label="标签文档" align="center" class-name="small-padding fixed-width" prop="blabelCheck" width="80px">-->
<!--        <template slot-scope="scope">-->
<!--          <el-checkbox v-model="scope.row.blabelCheck"></el-checkbox>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="包装单" align="center" class-name="small-padding fixed-width" prop="bpackageCheck" width="60px">-->
<!--        <template slot-scope="scope">-->
<!--          <el-checkbox v-model="scope.row.bpackageCheck"></el-checkbox>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="是否缺料" align="center" prop="missingMaterial"  width="80px"/>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80px" fixed="right">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleAdjust(scope.row)"-->
<!--            v-hasPermi="['factory:factorywplan:edit']"-->
<!--          >调整排产</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 排产调整对话框 -->
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="800px"
      append-to-body
    >
      <div style="margin-bottom: 20px;text-align: center;">
        <el-row :gutter="16">
          <el-col :span="4" style="margin-right: 100px;">
            <div>
              计划开始日期：
              <el-date-picker
                clearable
                v-model="adjustWplanSelected.wplanStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="计划开始日期"
                @change="wplanDateChange"
              >
              </el-date-picker>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              计划结束日期：
              <el-date-picker
                clearable
                v-model="adjustWplanSelected.wplanEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="计划结束日期"
                @change="wplanDateChange"
              >
              </el-date-picker>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="adjustWplanSelected.wplanDetailList">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="排产日期" align="center" prop="planDate" width="300">
          <template slot-scope="scope">
            <el-date-picker
              clearable
              v-model="scope.row.planDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始时间"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="排产数量" align="center" prop="planCapacity" width="200px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.planCapacity" placeholder="排产数量" clearable ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.$index>0"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="wplanDateRemove(scope.row)"
              v-hasPermi="['factory:factorywplan:edit']"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排产调整对话框
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="500px"
      append-to-body
    >
      <el-form ref="form2" :model="form2" :rules="rules" label-width="120px">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="wplanStartDate">
              <el-date-picker
                clearable
                v-model="form2.wplanStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="完成时间" prop="wplanEndDate">
              <el-date-picker
                clearable
                v-model="form2.wplanEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择完成时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
  import { printFactorywplan, listFactoryPrintwplan,printPlan,adjustWplan,getWeekOfMonth, weekViewList} from "@/api/sm/factory/factorywplan";
  import { planBigPanList, printPlanReport } from "@/api/sm/order/orderplan";
  import { listTeam,listFactory } from "@/api/system/dept";
  import moment from "moment";

  export default {
    name: "Orderinfo",
    dicts: ['order_status'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        teamSelect: true,
        planCal: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        plantotal: 0,
        //分厂待排产订单信息表格数据
        teamWplanList: [],
        adjustWplanSelected: {},
        teamList: [],
        monthList: [
          {
            "label": "2024年1月",
            "value": '2024-01'
          },
          {
            "label": "2024年2月",
            "value": '2024-02'
          },
          {
            "label": "2024年3月",
            "value": '2024-03'
          },
          {
            "label": "2024年4月",
            "value": '2024-04'
          },
          {
            "label": "2024年5月",
            "value": '2024-05'
          },
          {
            "label": "2024年6月",
            "value": '2024-06'
          },
          {
            "label": "2024年7月",
            "value": '2024-07'
          },
          {
            "label": "2024年8月",
            "value": '2024-08'
          },
          {
            "label": "2024年9月",
            "value": '2024-09'
          },
          {
            "label": "2024年10月",
            "value": '2024-10'
          },
          {
            "label": "2024年11月",
            "value": '2024-11'
          },
          {
            "label": "2024年12月",
            "value": '2024-12'
          }
        ],
        weekList: [
          {
            "label": "第1周",
            "value": '-1'
          },
          {
            "label": "第2周",
            "value": '-2'
          },
          {
            "label": "第3周",
            "value": '-3'
          },
          {
            "label": "第4周",
            "value": '-4'
          },
          {
            "label": "第5周",
            "value": '-5'
          }
        ],
        planStatusList: [
          {
            "label": "待排产",
            "value": 0
          },
          {
            "label": "排产完成",
            "value": 1
          }
        ],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        adjustopen: false,
        // 同步时间时间范围
        daterangeOrderDate: [],
        factoryList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          teamId: null,
          month: null,
          week: null,
          orderCode: null,
          contractCode: null,
          teamIds: [],
          plan_months: null,
        },
        // 表单参数
        form: {
          planMonth: null,
          workOrderIds: null
        },
        form2: {
          id: null,
          wplanStartDate: null,
          wplanEndDate: null
        },
        // 表单参数
        form1: {
          wplanList: null
        },
        // 表单校验
        rules: {
        },
      };
    },
    created() {
      this.init();
      this.queryParams.month = this.getCurrentDate();
      this.getWeekOfMonth();
      this.getFactoryList();
      // this.getTeamList();
      this.getList();
    },
    methods: {
      init() {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，然后确保是两位数
        const day = currentDate.getDate().toString().padStart(2, '0'); // 获取日并确保是两位数
        this.queryParams.plan_months = `${year}-${month}`;
      },
      customColorMethod(percentage) {
        if (percentage < 10) {
          return '#f56c6c';
        } else if (percentage < 30) {
          return '#909399';
        } else if (percentage < 70) {
          return '#e6a23c';
        } else {
          return '#67c23a';
        }
      },
      getFirstMondayOfMonth(date) {
        // 将日期设置为当月的第一天
        date.setDate(1);

        // 获取当月第一天是周几
        let dayOfWeek = date.getDay();

        // 如果当月的第一天就是周一，那么就是当月的第一个周一
        if (dayOfWeek === 1) {
          return date;
        }

        // 如果当月的第一天不是周一，那么就往前数(7 - dayOfWeek + 1)天
        date.setDate(date.getDate() + (7-dayOfWeek + 1));
        return date;
      },
      getWeekOfMonth(){
        let date = new Date(); // 当前日期
        let firstMonday = this.getFirstMondayOfMonth(date);
        let days = this.selectDay((Date.parse(firstMonday))/1000);
        var weeks =Math.ceil(14/7);
        this.queryParams.week="-"+weeks;
      },
      selectDay(starttime){
        var today=(Date.parse(new Date()))/1000;//当前时间戳
        var nTime = today - starttime;
        var day =Math.floor(nTime/86400);
        return day;
      },

      formatDateToYYYYMMDD(date) {
        const year = date.getFullYear();
        let month = date.getMonth() + 1; // 月份是从 0 开始的，需要加 1
        let day = date.getDate();

        // 如果月份或日期小于 10，前面补零
        if (month < 10) {
          month = '0' + month;
        }
        if (day < 10) {
          day = '0' + day;
        }
        return `${year}-${month}-${day}`;
      },
      wplanDateRemove(row) {
        let wplanList = this.adjustWplanSelected.wplanDetailList;
        if (wplanList.length === 0) {
          alert('已经无日期删除');
        }
        for(let i=0;i<wplanList.length;i++) {
          let obj = wplanList[i];
          if (obj.planDate === row.planDate) {
            wplanList.splice(i, 1);
            break;
          }
        }
      },
      wplanDateChange() {
        let wplanDetailList = this.adjustWplanSelected.wplanDetailList;
        if (wplanDetailList.length === 0) {
          alert('已经无日期调整');
        }
        let cloneSrcObject = this.adjustWplanSelected.wplanDetailList[0];
        const start = new Date(this.adjustWplanSelected.wplanStartDate);
        const end = new Date(this.adjustWplanSelected.wplanEndDate);
        // 循环变量从起始日期开始，逐天增加
        let currentDate = new Date(start);
        while (currentDate <= end) {
          let curPlanDate = this.formatDateToYYYYMMDD(currentDate);
          const exists = this.adjustWplanSelected.wplanDetailList.some(item => item.planDate === curPlanDate);
          if (!exists) {
            let rowWPlan = {};
            Object.assign(rowWPlan, cloneSrcObject);
            rowWPlan.planCapacity = 0;
            rowWPlan.planDate = curPlanDate;
            this.adjustWplanSelected.wplanDetailList.push(rowWPlan);
          }
          // 增加一天
          currentDate.setDate(currentDate.getDate() + 1);
        }
      },
      getCurrentDate() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1; // 月份是从0开始的，所以需要加1
        return `${year}-${month.toString().padStart(2, '0')}`;
      },
      /** 调整排产日期功能 提交按钮 */
      submitAdjustForm() {
        if(this.adjustWplanSelected.wplanEndDate<this.adjustWplanSelected.wplanStartDate){
          alert("完成时间不能小于开始时间");
          return;
        }
        adjustWplan(this.adjustWplanSelected).then(response => {
          this.$modal.msgSuccess("周排产调整成功");
          this.adjustopen = false;
          this.getList();
        });
      },
      cancel2() {
        this.adjustopen = false;
        this.reset2();
      },
      reset2(){
        this.form2 = {
          id: null,
          wplanStartDate: null,
          wplanEndDate: null
        };
        this.resetForm("form2");
      },
      handleAdjust(row) {
        this.reset2();
        this.adjustopen = true;
        this.adjustWplanSelected = row;
        // this.form2.id = row.id;
        // this.form2.wplanStartDate = row.wplanStartDate;
        // this.form2.wplanEndDate = row.wplanEndDate;
      },

      //打印周计划
      printPlan() {
        printFactorywplan(this.queryParams).then(response => {
          let blob = new Blob([response], { type: "application/vnd.ms-excel" });
          var downloadElement = document.createElement("a");

          var href = window.URL.createObjectURL(blob); //创建下载的链接

          downloadElement.href = href;

          downloadElement.download = '周排产_工单'; //下载后文件名

          document.body.appendChild(downloadElement);

          downloadElement.click(); //点击下载

          document.body.removeChild(downloadElement); //下载完成移除元素

          window.URL.revokeObjectURL(href); //释放掉blob对象

          this.loading = false;
        });
      },
      getFactoryList() {
        this.loading = true;
        listFactory({"level":2}).then(response => {
          this.factoryList = response.data;

          // this.queryParams.factoryId = this.factoryList[0].deptId;
          // this.getTeamList(this.queryParams.factoryId);
          this.teamList = [];

          this.loading = false;
        });
      },
      factoryChange(){
        this.getTeamList(this.queryParams.factoryId);
      },
      /** 查询订单信息列表 */
      getTeamList(parentId) {
        this.loading = true;
        listTeam({"parentId":parentId}).then(response => {
          this.teamList = response.data || [];
          if (this.teamList) {
            this.teamList.splice(0, 0, {deptId: -1, deptName: "全部"});
            this.queryParams.teamIds = this.teamList.map(item => item.deptId);
          }
          this.loading = false;
        });
      },

      handlePrint() {
        this.queryParams.plan_month = "";
        if (Array.isArray(this.queryParams.plan_months)) {
          for (let i = 0; i < this.queryParams.plan_months.length; i++) {
            if (i != this.queryParams.plan_months.length - 1) {
              this.queryParams.plan_month += this.queryParams.plan_months[i] + ",";
            } else {
              this.queryParams.plan_month += this.queryParams.plan_months[i];
            }
          }
        } else {
          this.queryParams.plan_month = this.queryParams.plan_months;
        }
        this.loading = true;
        printPlanReport(this.queryParams).then(response => {
          let blob = new Blob([response], { type: "application/vnd.ms-excel" });
          var downloadElement = document.createElement("a");

          var href = window.URL.createObjectURL(blob); //创建下载的链接

          downloadElement.href = href;

          downloadElement.download = '生产计划排产周'; //下载后文件名

          document.body.appendChild(downloadElement);

          downloadElement.click(); //点击下载

          document.body.removeChild(downloadElement); //下载完成移除元素

          window.URL.revokeObjectURL(href); //释放掉blob对象

          this.loading = false;
        });
      },

      /** 查询订单信息列表 */
      getList() {
        if (!this.queryParams.plan_months) {
          this.$modal.msgError("请选择排产月份");
          return;
        }
        this.loading = true;
        // if (this.queryParams.teamId && this.queryParams.teamId === -1) {
        //   this.queryParams.teamId = null;// 全选，则不添加班组条件
        // }
        // this.queryParams.monthWeek=this.queryParams.month;
        this.queryParams.plan_month = "";
        if (Array.isArray(this.queryParams.plan_months)) {
          for (let i = 0; i < this.queryParams.plan_months.length; i++) {
            if (i != this.queryParams.plan_months.length - 1) {
              this.queryParams.plan_month += this.queryParams.plan_months[i] + ",";
            } else {
              this.queryParams.plan_month += this.queryParams.plan_months[i];
            }
          }
        } else {
          this.queryParams.plan_month = this.queryParams.plan_months;
        }

        // listFactoryPrintwplan(this.queryParams).then(response => {
        //   this.teamWplanList = response.data;
        //   this.total = response.total;
        //   this.loading = false;
        // });
        planBigPanList(this.queryParams).then(response => {
          this.teamWplanList = response.rows || [];
          this.total = response.total;
          this.loading = false;
        }).catch(error => {
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        // if(this.queryParams.teamId==null || this.queryParams.teamId==undefined){
        //   alert("请先选择班组,打印月份，周数后才能查询");
        //   return;
        // }
        // if(this.queryParams.month==null || this.queryParams.month==undefined){
        //   alert("请先选择班组,打印月份才能查询");
        //   return;
        // }
        // if(this.queryParams.week==null || this.queryParams.week==undefined){
        //   alert("请先选择班组,打印月份，周数后才能查询");
        //   return;
        // }
        this.teamSelect = false;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeOrderDate = [];
        this.resetForm("queryForm");
        // this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
    }
  };
</script>
